package com.chens.modules.system.service;

import com.chens.modules.system.model.User;
import com.chens.modules.system.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Service
public class UserService {

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private PasswordEncoder passwordEncoder;

    public List<User> getAllUsers() {
        return userRepository.findAll();
    }

    public Optional<User> getUserById(Long id) {
        return userRepository.findById(id);
    }

    public User updateUser(Long id, User userDetails) {
        // 检查用户是否存在
        if (!userRepository.existsById(id)) {
            throw new RuntimeException("用户不存在");
        }

        // 检查用户名是否已存在，排除当前用户
        if (userRepository.existsByUsernameAndIdNot(userDetails.getUsername(), id)) {
            throw new RuntimeException("用户名已存在");
        }

        // 检查邮箱是否已存在，排除当前用户
        if (userRepository.existsByEmailAndIdNot(userDetails.getEmail(), id)) {
            throw new RuntimeException("邮箱已存在");
        }

        return userRepository.findById(id)
                .map(user -> {
                    user.setUsername(userDetails.getUsername());
                    user.setNickname(userDetails.getNickname());
                    user.setEmail(userDetails.getEmail());
                    user.setRole(userDetails.getRole());
                    return userRepository.save(user);
                })
                .orElse(null);
    }

    public void deleteUser(Long id) {
        userRepository.deleteById(id);
    }

    public User registerUser (User user) throws RuntimeException{
        // 检查用户名是否已存在
        if (userRepository.existsByUsername(user.getUsername())) {
            throw new RuntimeException("用户名已存在");
        }

        // 检查邮箱是否已存在
        if (userRepository.existsByEmail(user.getEmail())) {
            throw new RuntimeException("邮箱已存在");
        }

        // 设置默认角色
        user.setRole("ROLE_USER");

        // 加密密码
        user.setPassword(passwordEncoder.encode(user.getPassword()));

        return userRepository.save(user);
    }

    public Page<User> getUsers(int page, int size) {
        // 页码从0开始
        Pageable pageable = PageRequest.of(page - 1, size);
        return userRepository.findAll(pageable);
    }
}